import React from 'react';
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import {
    Card, Steps, Button, Space,
    Input, Row, Col, Tabs, Modal,
    Form, DatePicker, Select,
    Checkbox, Table, InputNumber, message
} from 'antd';
import {
    PlusOutlined,
    CloseOutlined,
    ExclamationCircleOutlined,
} from '@ant-design/icons';
import { connect } from 'umi';
import * as Request from '@/services/Request';
import moment from 'moment';
import CateComp from '@/components/CategoryComponent';
import PartSelect from '@/components/PartSelect';
import SoSelect from '@/components/SoSelect';

const { Step } = Steps;
const { TabPane } = Tabs;
const { confirm } = Modal;
const apiURL = "/api/services/app/OrderHed/";
const apiURLDtl = "/api/services/app/OrderDtl/";
const apiURLRel = "/api/services/app/OrderRel/";
const apiURLCust = "/api/services/app/Customers/";
class ViewPage extends React.Component<any, any> {
    constructor(props: Readonly<{}>) {
        super(props);
        this.state = {
            data: { orderNum: 0 },
            orderDtl: { orderNum: 0, orderLine: 0 },
            orderRel: { orderNum: 0, orderLine: 0, orderRelNum: 0 },
            loading: false,
            visible: false,
            dataSource: [],
            optionCust: [],
            defTab: '1',
        }
    }
    formRef: any = React.createRef();
    componentDidMount() {
        this.fetchCust();
        this.fetchCate();
    }
    onFinish = (values: { order: any; orderDtl: any; orderRel: any; }) => {
        var orderHed = values.order;
        var orderDtl = values.orderDtl;
        var orderRel = values.orderRel;
        const { data } = this.state;
        orderHed.id = data.id;
        try {
            orderHed.requestDate = orderHed?.requestDate.format('YYYY-MM-DD');
            orderHed.orderDate = orderHed?.orderDate.format('YYYY-MM-DD');

            if (orderDtl) {
                orderDtl.requestDate = orderDtl?.requestDate.format('YYYY-MM-DD');
                orderDtl.qsDate = orderDtl?.qsDate.format('YYYY-MM-DD');
                orderDtl.warrantyDate = orderDtl?.warrantyDate.format('YYYY-MM-DD');
            }
            if (orderRel) {
                orderRel.requestDate = orderRel?.requestDate.format('YYYY-MM-DD');
            }
            Request.post(apiURL + 'Modify', orderHed).then((response) => {
                if (response) {
                    if (response.success) {
                        message.success('保存成功！');
                    }
                    else {
                        message.error(response.error.message);
                    }
                    this.setState({ loading: false });
                }
            });
            if (orderDtl && orderDtl.id) {
                orderDtl.orderNum = orderHed.orderNum
                Request.post(apiURLDtl + 'Modify', [orderDtl]).then((response) => {
                    if (response) {
                        if (response.success) {
                            message.success('分录保存成功！');
                        }
                        else {
                            message.error(response.error.message);
                        }
                        this.setState({ loading: false });
                    }
                });
            }
            if (orderRel && orderRel.id) {
                orderRel.orderNum = orderHed.orderNum
                orderRel.orderLine = orderDtl.orderLine
                Request.post(apiURLRel + 'Modify', [orderRel]).then((response) => {
                    if (response) {
                        if (response.success) {
                            message.success('发货行保存成功！');
                        }
                        else {
                            message.error(response.error.message);
                        }
                        this.setState({ loading: false });
                    }
                });
            }
            this.getObj(orderHed)
        } catch (error) {
            console.log(error);
            message.error("发生错误，请联系管理员");
        }

    }
    fetchCust = () => {
        this.setState({ loading: true });
        Request.get(apiURLCust + 'GetAll?SkipCount=0&MaxResultCount=10000').then((response) => {
            if (response) {
                if (response.success) {
                    var items = response.result?.items;
                    this.setState({ optionCust: items });
                }
                else {
                    message.error(response.error.message);
                }
            }
            this.setState({ loading: false });
        });
    };
    fetchCate = () => {
        this.props.dispatch({
            type: 'Abp/getTreeList',
            payload: { layout: 'Currency' },
            control: 'Category'
        }).then(() => {
            this.setState({ optionCurrency: this.props.response.result });
        })
        this.props.dispatch({
            type: 'Abp/getTreeList',
            payload: { layout: 'ShipVia' },
            control: 'Category'
        }).then(() => {
            this.setState({ optionShipVia: this.props.response.result });
        })
    }
    newObj = () => {
        const { currentUser } = this.props;
        var value = {
            entryPerson: currentUser.userName,
        };
        Request.post(apiURL + 'New', value).then((response) => {
            if (response) {
                if (response.success) {
                    message.success('新建订单成功！');
                    var order = response.result.data;
                    this.setState({ data: order });
                    this.formRef.current.setFieldsValue({ order });
                }
                else {
                    message.error(response.error.message);
                }
                this.setState({ loading: false });
            }
        });
    }
    newDtl = () => {
        const { data } = this.state;
        if (data.orderNum == 0) {
            message.warning("请先创建销售订单");
            return;
        }
        var value = {
            orderNum: data.orderNum,
            partNum: '',
            lineDesc: '',
        };
        Request.post(apiURLDtl + 'New', value).then((response) => {
            if (response) {
                this.setState({ loading: true });
                if (response.success) {
                    var data = response.result.data;
                    this.formRef.current.setFieldsValue({ orderDtl: data });
                    this.setState({ defTab: '2', orderDtl: data })
                }
                else {
                    message.error(response.error.message);
                }
                this.setState({ loading: false });
            }
        });
    }
    newRel = () => {
        const { orderDtl } = this.state;
        if (orderDtl.orderNum == 0 || orderDtl.orderLine == 0) {
            message.warning("请先创建销售订单分录");
            return;
        }
        var value = {
            orderNum: orderDtl.orderNum,
            orderLine: orderDtl.orderLine,
        };
        Request.post(apiURLRel + 'New', value).then((response) => {
            if (response) {
                this.setState({ loading: true });
                if (response.success) {
                    var data = response.result.data;
                    this.formRef.current.setFieldsValue({ orderRel: data });
                    this.setState({ defTab: '3', orderRel: data })
                }
                else {
                    message.error(response.error.message);
                }
                this.setState({ loading: false });
            }
        });
    }
    delObj = () => {
        const { data } = this.state
        let _this = this
        confirm({
            title: '警告',
            icon: <ExclamationCircleOutlined />,
            content: '删除后将不可恢复，确定删除？',
            onOk() {
                _this.props.dispatch({
                    type: 'Abp/delete',
                    payload: { id: data.id },
                    control: 'OrderHed'
                }).then(() => {
                    _this.formRef.current.resetFields()
                    _this.setState({ data: { orderNum: 0 } })
                })
            },
        });
    }
    delDtl = () => {
        const { selectedRowKeys, orderDtls } = this.state
        let _this = this
        confirm({
            title: '警告',
            icon: <ExclamationCircleOutlined />,
            content: '删除后将不可恢复，确定删除？',
            onOk() {
                _this.props.dispatch({
                    type: 'Abp/delPatch',
                    payload: selectedRowKeys,
                    control: 'OrderDtl'
                }).then(() => {
                    let lists = orderDtls.filter((o: any) => selectedRowKeys.indexOf(o.id) < 0)
                    _this.setState({ orderDtls: lists })
                })
            },
        });
    }
    delRel = () => {
        const { selectedRowKeys2, orderRels } = this.state
        let _this = this
        confirm({
            title: '警告',
            icon: <ExclamationCircleOutlined />,
            content: '删除后将不可恢复，确定删除？',
            onOk() {
                _this.props.dispatch({
                    type: 'Abp/delPatch',
                    payload: selectedRowKeys2,
                    control: 'OrderRel'
                }).then(() => {
                    let lists = orderRels.filter((o: any) => selectedRowKeys2.indexOf(o.id) < 0)
                    _this.setState({ orderRels: lists })
                })
            },
        });
    }
    getObj = (e: any) => {
        if (e.orderNum) {
            this.setState({ loading: true });
            Request.get(apiURL + 'GetByNum?num=' + e.orderNum).then((response) => {
                if (response) {
                    if (response.success) {
                        if (response.result.success) {
                            var orderHed = response.result.data;
                            if (orderHed.orderDate)
                                orderHed.orderDate = moment(orderHed.orderDate);
                            if (orderHed.requestDate)
                                orderHed.requestDate = moment(orderHed.requestDate);
                            this.setState({ data: orderHed, orderDtls: orderHed.items, orderRels: orderHed.items[0]?.items });
                            this.formRef.current.setFieldsValue({ order: orderHed });
                            if(orderHed.items && orderHed.items.length>0)
                                this.setOrderDtl(orderHed.items[0])
                        }
                        else {
                            message.error(response.result.message);
                        }
                    }
                    else {
                        message.error(response.error.message);
                    }
                    this.setState({ loading: false });
                }
            });
        }
    }
    openModal = (record: any, layout: string) => {
        this.setState({ visible: true, disabled: true, record, layout });
    }
    closeModal = () => {
        this.setState({ visible: false });
    }
    setCurrent = (part?: any) => {
        if (part) {
            var orderDtl: any = {};
            orderDtl.partNum = part.partNum;
            orderDtl.lineDesc = part.partDescription;
            orderDtl.ium = part.ium;
            this.formRef.current.setFieldsValue({ orderDtl });
            this.setState({ partRevs: part.revs });
        }
    }
    setOrderDtl = (orderDtl: any) => {
        if (orderDtl.requestDate)
            orderDtl.requestDate = moment(orderDtl.requestDate);
        if (orderDtl.warrantyDate)
            orderDtl.warrantyDate = moment(orderDtl.warrantyDate);
        if (orderDtl.qsDate)
            orderDtl.qsDate = moment(orderDtl.qsDate);
        this.formRef.current.setFieldsValue({ orderDtl });
        this.setState({ orderRels: orderDtl.items, defTab: '2', orderDtl })
        if(orderDtl.items && orderDtl.items.length>0)
            this.setOrderRel(orderDtl.items[0])
    }
    setOrderRel = (orderRel: any) => {
        if (orderRel.requestDate)
            orderRel.requestDate = moment(orderRel.requestDate);
        this.formRef.current.setFieldsValue({ orderRel });
        this.setState({ defTab: '3', orderRel })
    }
    tabSwitch = (key: any) => {
        this.setState({ defTab: key });
    }
    onSelectChange = (selectedRowKeys: any) => {
        this.setState({ selectedRowKeys });
    };
    onSelectChange2 = (selectedRowKeys2: any) => {
        this.setState({ selectedRowKeys2 });
    };
    render() {
        const { data, defTab, selectedRowKeys, selectedRowKeys2 } = this.state
        const layout = {
            labelCol: { span: 5 },
            wrapperCol: { span: 19 },
        };
        const columns = [
            {
                title: '项目',
                dataIndex: 'orderLine',
                key: 'orderLine',
            },
            {
                title: '未结',
                dataIndex: 'openLine',
                key: 'openLine',
                render: (text: boolean) => (
                    <Checkbox checked={text} />
                )
            },
            {
                title: '产品',
                dataIndex: 'partNum',
                key: 'partNum',
            },
            {
                title: '产品描述',
                dataIndex: 'lineDesc',
                key: 'lineDesc',
            },
            {
                title: '销售数量',
                dataIndex: 'orderQty',
                key: 'orderQty',
            },
            {
                title: '单价',
                dataIndex: 'unitPrice',
                key: 'unitPrice',
            },
        ];
        const columnRel = [
            {
                title: '项目',
                dataIndex: 'orderRelNum',
                key: 'orderRelNum',
            },
            {
                title: '订单数量',
                dataIndex: 'ourReqQty',
                key: 'ourReqQty',
            },
            {
                title: '未结',
                dataIndex: 'openRelease',
                key: 'openRelease',
                render: (text: boolean) => (
                    <Checkbox checked={text} />
                )
            },
            {
                title: '需求日',
                dataIndex: 'requestDate',
                key: 'requestDate',
                render: (text: any) => (
                    <span>{moment(text).format('YYYY-MM-DD')}</span>
                )
            },
            {
                title: '直接生产',
                dataIndex: 'make',
                key: 'make',
                render: (text: boolean) => (
                    <Checkbox checked={text} />
                )
            },
            {
                title: '直接采购',
                dataIndex: 'buyToOrder',
                key: 'buyToOrder',
                render: (text: boolean) => (
                    <Checkbox checked={text} />
                )
            },

        ];
        const selectRev = <Select
            placeholder="选择版本" >
            {
                this.state.partRevs?.map((item: any) => {
                    return (<Select.Option key={item} value={item}>{item}</Select.Option>)
                })
            }
        </Select>
        const optionCust = this.state.optionCust?.map((d: any) => {
            return (
                <Select.Option value={d.custNum} key={d.id}>
                    {d.customerName}
                </Select.Option>)
        });
        const rowSelection = {
            selectedRowKeys,
            onChange: this.onSelectChange,
        };
        const rowSelection2 = {
            selectedRowKeys2,
            onChange: this.onSelectChange2,
        };
        return (
            <PageHeaderWrapper>
                <Card style={{ marginBottom: 16 }}>
                    <Steps current={4}>
                        <Step title="配置" description="配置您的公司信息" />
                        <Step title="客户信息" description="导入或创建客户" />
                        <Step title="报价单模板" description="自定义一份报价单模板" />
                        <Step title="付款方式" description="选择您的默认客户付款方式" />
                        <Step title="示例" description="发送一份SO订单示例" />
                    </Steps>
                </Card>
                <Form {...layout} ref={this.formRef} onFinish={this.onFinish} >

                    <Row gutter={16}>
                        <Col span={12}>
                            <Card extra={
                                <Space>
                                    <Button type="primary" icon={<PlusOutlined />} onClick={() => this.newObj()}>新增</Button>
                                    <Button type="primary" htmlType="submit">保存</Button>
                                    <Button danger icon={<CloseOutlined />} disabled={data.orderNum === 0} onClick={this.delObj}>删除</Button>
                                </Space>
                            }>
                                <Tabs defaultActiveKey={defTab} activeKey={defTab} onChange={this.tabSwitch}>
                                    <TabPane tab="汇总" key="1">
                                        <Form.Item wrapperCol={{ offset: 5 }} style={{ marginBottom: 0 }}>
                                            <Input.Group compact>
                                                <Form.Item name={['order', 'openOrder']} valuePropName="checked">
                                                    <Checkbox>未结</Checkbox>
                                                </Form.Item>
                                                <Form.Item name={['order', 'approve']} valuePropName="checked">
                                                    <Checkbox>核准</Checkbox>
                                                </Form.Item>
                                                <Form.Item name={['order', 'voidOrder']} valuePropName="checked">
                                                    <Checkbox>无效</Checkbox>
                                                </Form.Item>
                                            </Input.Group>
                                        </Form.Item>
                                        <Form.Item label="订单号">
                                            <Input.Group compact>
                                                <SoSelect
                                                    width={180}
                                                    noStyle
                                                    name={['order', 'orderNum']}
                                                    rules={[{ required: true, message: "请输入订单号" }]}
                                                    setCurrent={this.getObj} />
                                            </Input.Group>
                                        </Form.Item>
                                        <Form.Item name={['order', 'custNum']} label="选择客户">
                                            <Select
                                                style={{ width: 240 }}
                                                showSearch
                                                placeholder="请选择客户"
                                                filterOption={(input, option: any) =>
                                                    option.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
                                                }
                                            >
                                                {optionCust}
                                            </Select>
                                        </Form.Item>
                                        <CateComp layout="Currency" width={200} name={['order', 'currencyCode']} label="货币类型" />
                                        <CateComp layout="ShipVia" width={200} name={['order', 'shipViaCode']} label="运输方法" />
                                        <Form.Item
                                            name={['order', 'orderDate']}
                                            label="订单日期"
                                            rules={[{ required: true, message: "请选择到期日" }]}>
                                            <DatePicker />
                                        </Form.Item>
                                        <Form.Item
                                            name={['order', 'requestDate']}
                                            label="需求日期"
                                            rules={[{ required: true, message: "请选择需求日期" }]}>
                                            <DatePicker />
                                        </Form.Item>
                                        <Form.Item name={['order', 'projectNum']} label="项目号">
                                            <Input style={{ width: 200 }} />
                                        </Form.Item>
                                        <Form.Item name={['order', 'pONum']} label="客户PO号">
                                            <Input style={{ width: 200 }} />
                                        </Form.Item>

                                    </TabPane>
                                    <TabPane tab="分录明细" key="2">
                                        <Form.Item name={['orderDtl', 'id']} hidden={true}>
                                            <Input />
                                        </Form.Item>
                                        <Form.Item label="分录" name={['orderDtl', 'orderLine']}>
                                            <InputNumber disabled />
                                        </Form.Item>
                                        <Form.Item label="产品编码" style={{ marginBottom: 0 }}>
                                            <Input.Group compact>
                                                <PartSelect name={['orderDtl', 'partNum']} width={200} required={true} placeholder="产品编码" setCurrent={this.setCurrent} />
                                                <Form.Item name={['orderDtl', 'ium']}>
                                                    <Input placeholder="单位" style={{width:60}} disabled />
                                                </Form.Item>
                                                <Form.Item
                                                    name={['orderDtl', 'revisionNum']}
                                                    rules={[{ required: true, message: "请输入版本" }]}>
                                                    {selectRev}
                                                </Form.Item>                                                
                                            </Input.Group>
                                        </Form.Item>

                                        <Form.Item
                                            name={['orderDtl', 'lineDesc']}
                                            label="产品描述">
                                            <Input.TextArea readOnly disabled />
                                        </Form.Item>
                                        <Form.Item
                                            name={['orderDtl', 'unitPrice']}
                                            label="单价"
                                            rules={[{ required: true, message: "请输入单价" }]}>
                                            <Input prefix="￥" suffix="RMB" style={{ width: 200 }} />
                                        </Form.Item>
                                        <Form.Item
                                            name={['orderDtl', 'discount']}
                                            label="折扣">
                                            <Input suffix="%" style={{ width: 100 }} />
                                        </Form.Item>
                                        <Form.Item
                                            name={['orderDtl', 'requestDate']}
                                            label="需求日期"
                                            rules={[{ required: true, message: "请选择需求日期" }]}>
                                            <DatePicker />
                                        </Form.Item>
                                        <Form.Item
                                            name={['orderDtl', 'warrantyDate']}
                                            label="保修期"
                                            rules={[{ required: true, message: "请选择保修期" }]}>
                                            <DatePicker />
                                        </Form.Item>
                                        <Form.Item
                                            name={['orderDtl', 'qsDate']}
                                            label="质保期"
                                            rules={[{ required: true, message: "请选择质保期" }]}>
                                            <DatePicker />
                                        </Form.Item>
                                    </TabPane>
                                    <TabPane tab="发货明细" key="3">
                                        <Form.Item name={['orderRel', 'id']} hidden={true}>
                                            <Input />
                                        </Form.Item>
                                        <Form.Item label="发货行" name={['orderRel', 'orderRelNum']}>
                                            <InputNumber disabled />
                                        </Form.Item>
                                        <Form.Item
                                            name={['orderRel', 'ourReqQty']}
                                            label="订单数量"
                                            rules={[{ required: true, message: "请输入订单数量" }]}>
                                            <InputNumber min={1} />
                                        </Form.Item>
                                        <Form.Item
                                            name={['orderRel', 'requestDate']}
                                            label="需求日期"
                                            rules={[{ required: true, message: "请选择出货日期" }]}>
                                            <DatePicker />
                                        </Form.Item>
                                        <CateComp layout="ShipVia" width={200} name={['orderRel', 'shipViaCode']} label="运输方法" />
                                        <Form.Item wrapperCol={{ offset: 5 }} style={{ marginBottom: "0px" }}>
                                            <Input.Group compact>
                                            <Form.Item name={['orderRel', 'openRelease']} valuePropName="checked">
                                                    <Checkbox>未结</Checkbox>
                                                </Form.Item>
                                                <Form.Item name={['orderRel', 'buyToOrder']} valuePropName="checked">
                                                    <Checkbox>直接出货</Checkbox>
                                                </Form.Item>
                                                <Form.Item name={['orderRel', 'make']} valuePropName="checked">
                                                    <Checkbox>直接生产</Checkbox>
                                                </Form.Item>
                                            </Input.Group>
                                        </Form.Item>
                                    </TabPane>
                                    <TabPane tab="联系人" key="4">
                                        <Form.Item
                                            name={['order', 'contactor']}
                                            label="联系人"
                                            rules={[{ required: true, message: "请输入联系人" }]}>
                                            <Input style={{ width: 200 }} />
                                        </Form.Item>
                                        <Form.Item name={['order', 'phoneNum']} label="联系电话">
                                            <Input style={{ width: 200 }} />
                                        </Form.Item>
                                        <Form.Item name={['order', 'emailAddress']}
                                            rules={[{ required: true, message: "请输入电子邮件" }]}
                                            label="电子邮件">
                                            <Input style={{ width: 200 }} />
                                        </Form.Item>
                                        <Form.Item
                                            name={['order', 'address']}
                                            label="联系地址">
                                            <Input.TextArea />
                                        </Form.Item>
                                    </TabPane>
                                    <TabPane tab="订单备注" key="5">
                                        <Form.Item
                                            name={['order', 'orderComment']} >
                                            <Input.TextArea rows={10} />
                                        </Form.Item>
                                    </TabPane>
                                </Tabs>
                            </Card>
                        </Col>
                        <Col span={12}>
                            <Card>
                                <Tabs defaultActiveKey="1" >
                                    <TabPane tab="分录项" key="1">
                                        <Table rowKey="id" size="small" columns={columns} dataSource={this.state.orderDtls}
                                            onRow={record => {
                                                return {
                                                    onClick: event => { this.setOrderDtl(record) },
                                                };
                                            }}
                                            rowSelection={rowSelection}
                                        />
                                        <Row gutter={16}>
                                            <Col span={12}><Button block type="dashed" icon={<PlusOutlined />} onClick={this.newDtl}>添加分录</Button></Col>
                                            <Col span={12}><Button block danger icon={<CloseOutlined />} onClick={this.delDtl}>删除分录</Button></Col>
                                        </Row>

                                    </TabPane>
                                    <TabPane tab="发货行" key="2">
                                        <Table rowKey="id" size="small" columns={columnRel} dataSource={this.state.orderRels}
                                            onRow={record => {
                                                return {
                                                    onClick: event => { this.setOrderRel(record) },
                                                };
                                            }}
                                            rowSelection={rowSelection2}
                                        />
                                        <Row gutter={16}>
                                            <Col span={12}><Button block type="dashed" icon={<PlusOutlined />} onClick={this.newRel}>添加发货项</Button></Col>
                                            <Col span={12}><Button block danger icon={<CloseOutlined />} onClick={this.delRel}>删除发货项</Button></Col>
                                        </Row>

                                    </TabPane>
                                </Tabs>
                            </Card>
                        </Col>
                    </Row>
                </Form>
            </PageHeaderWrapper>
        )
    }
}
export default connect(({ Abp }: API.IConnectState) => ({
    response: Abp.response,
    currentUser: Abp.currentUser,
}))(ViewPage);